package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleHttpService;
import com.heima.article.service.ApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2023-01-03-21:51
 */
@Service
@Slf4j
public class ApArticleHttpServiceImpl implements ApArticleHttpService {


    @Autowired
    private ApArticleContentService apArticleContentService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleService apArticleService;

    /**
     * 异步生成文章详情页并上传
     * @param apArticle
     * @param contentStr
     */
    @GlobalTransactional
    @Async("taskExecutor")
    @Override
    public void generatorHtml(ApArticle apArticle, String contentStr) {
        try {
            //1.为FreeMarker准备模型数据
            //1.1根据文章id查询文章详情对象
            Long articleId = apArticle.getId();
            //1.2将文章详情数组字符串转换为数组对象
            JSONArray content = JSONArray.parseArray(contentStr);
            //1.3将文章详情数组数据存入Map中
            Map model = new HashMap();
            model.put("content",content);
            //2.使用FreeMarker生成文章详情数据
            //2.1构建临时空间存储空间对象StringWriter
            StringWriter out = new StringWriter();
            //2.2将文章详情数据存入到StringWriter
            Template template = configuration.getTemplate("article.ftl");
            //3.将文章详情数据传到minion
            template.process(model,out);
            //3.1将输出流转为输入流
            ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8));
            //3.2将文章详情数据上传到minion获取url
            String url = fileStorageService.uploadHtmlFile("", articleId+".html", in);
            //4.将文章的url更新到表ap_article中
            //4.1构建更新对象
            ApArticle article = new ApArticle();
            article.setId(articleId);
            article.setStaticUrl(url);
            //4.2执行更新
            boolean result = apArticleService.updateById(article);
            log.info("[文章详情页面生成完毕]文章id:{}",articleId);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
             throw new RuntimeException(e);
        }
    }
}
